package com.yc.sole.framework.utils;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yizuomin
 * @date 2022/11/29 17:47
 **/
public class ResponseUtil {

    /**
     * 返回登录超时的错误信息
     *
     * @param response ServletResponse
     */
    public static void returnResponse(ServletResponse response, Integer code, String result) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        // 设置返回响应编码
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("Application/json;charset=utf-8");
        // 构造返回响应体
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("message", result);
        map.put("success", false);
        String resultString = JSONUtil.toJsonStr(map);
        outputStream.write(resultString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
